package com.killer.process.impl;

import com.killer.anno.Autowired;
import com.killer.anno.Transaction;
import com.killer.factory.impl.AbstractApplicationContext;
import com.killer.pojo.BeanDefinition;
import com.killer.process.BeanPostProcessor;
import com.killer.transaction.PlatformTransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class AbstractAutoProxyCreator implements BeanPostProcessor {

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //获取该beanDefinition
        BeanDefinition beanDefinition = AbstractApplicationContext.getBeanDefinition(beanName);
        if (!beanDefinition.isNeedProxy()) {
            //不需要代理则直接返回
            return bean;
        }
        //这里为了简化，就不做判断了，直接使用cglib创建代理对象
        Object proxy=Enhancer.create(bean.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (method.getAnnotation(Transaction.class) != null) {
                    try {
                        if (platformTransactionManager == null) {
                            throw new RuntimeException("请自行实现事务控制代码");
                        }
                        platformTransactionManager.beginTransaction();
                        Object result = method.invoke(bean, objects);
                        platformTransactionManager.commit();
                        return result;
                    } catch (Exception e) {
                        platformTransactionManager.rollback();
                        throw new RuntimeException(e);
                    }
                }else{
                    return method.invoke(o, objects);
                }
            }
        });

        return proxy;
    }
}
